"use strict";

var C = require('../common'),
    express = require('express');

module.exports = {

    type: 'engine',

    load: function (owner, config, cb) {

        var engine = express();

        if (config.viewEngine === 'swig') {
            var swig = require('swig');
            engine.engine('swig', swig.renderFile);

            engine.set('view engine', 'swig');

            if ('development' === ENV) {
                swig.setDefaults({ cache: false });
            }

            owner.log('verbose', 'Used swig as view engine.');
        }

        // all environments
        engine.set('env', ENV);
        engine.set('views', './');


        if (config.caseSensitiveRouting) {
            engine.enable('case sensitive routing');
            owner.log('verbose', 'Enabled case-sensitive routing.');
        }

        engine.disable('x-powered-by');

        // view cache
        if ('development' === ENV) {
            engine.disable('view cache');
        }

        // middlewares
        var expressWinston = require('express-winston');
        var logger = require('./logger');
        var bodyParser = require('body-parser');
        //var cookieParser = require('cookie-parser');

        // access log
        if (config.accessLogger) {
            engine.use(expressWinston.logger(logger.processTransports(config.accessLogger)));
            owner.log('verbose', 'Enabled access logger.');
        }

        if (config.compression) {
            var compression = require('compression');
            engine.use(compression());
            owner.log('verbose', 'Enabled compression.');
        }

        config.documentRoot && (owner.documentRoot = config.documentRoot);

        var serveStatic = require('serve-static');
        engine.use(serveStatic(owner.documentRoot));
        owner.log('verbose', 'Enabled static root.');

        // parse application/x-www-form-urlencoded
        engine.use(bodyParser.urlencoded({extended: true}));

        // parse application/json
        engine.use(bodyParser.json());

        // parse application/vnd.api+json as json
        engine.use(bodyParser.json({ type: 'application/vnd.api+json' }));

        //engine.use(cookieParser());

        // error log
        if (config.errorLogger) {
            engine.use(expressWinston.errorLogger(logger.processTransports(config.errorLogger)));
            owner.log('verbose', 'Enabled error logger.');
        }

        // error handler
        if ('development' === ENV && config.devErrorHandler) {
            var errorHandler = require('errorhandler');
            engine.use(errorHandler(config.devErrorHandler));
        }

        owner.engine = engine;

        cb();
    }
};